<template>
  <div class="dashboard">
    <!-- 第一行图表 -->
    <el-row :gutter="20" justify="space-between" style="margin-top: 0px">
      <el-col :span="12">
        <el-card class="chart-card">
          <salary-chart :selected-date="salaryChartDate" style="width: 100%"
            @handle-date-change="handleSalaryDateChange" />
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="chart-card">
          <suixiao-chart :selected-date="suixiaoChartDate" style="width: 100%; height: 488px"
            @handle-date-change="handlesuixiaoDateChange" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行图表 -->
    <el-row :gutter="20" style="margin-top: 0px">
      <!-- 第一列 -->
      <el-col :span="8">
        <!-- 区县网格薪酬统计 -->
        <el-card class="chart-card">
          <wangge-chart :selected-date="gridChartDate" style="width: 100%; height: 433px"
            @handle-date-change="handleWanggeDateChange" />
        </el-card>

        <!-- 存量维护图表 -->
        <el-card>
          <circular-chart-with-fetch ref="maintenanceChart" :show-customer-type-filter="true" :customer-type-api-map="{
            home: '/maintainerSalary/homeAmountRatioByMonth',
            biz: '/maintainerSalary/bizAmountRatioByMonth',
          }" :first-option-label="'家宽'" :second-option-label="'企宽'" chart-title="存量维护" chart-type="pie"
            color-scheme="default" :chart-height="400" />
        </el-card>
      </el-col>

      <!-- 薪酬组成图表：各类薪酬占比饼图 -->
      <el-col :span="8">
        <el-card class="pie-chart-card">
          <salary-composition-chart :selected-date="salaryCompositionDate" class="pie-chart-wrapper"
            @handle-date-change="handleSalaryCompositionDateChange" />
        </el-card>

        <!-- 新装按次图表 -->
        <el-card>
          <circular-chart-with-fetch ref="installChart" :show-customer-type-filter="true" :customer-type-api-map="{
            home: '/maintainerSalary/homeSubtotalRatioByMonth',
            biz: '/maintainerSalary/bizSubtotalRatioByMonth',
          }" :first-option-label="'家客'" :second-option-label="'企客'" chart-title="新装按次" chart-type="pie"
            color-scheme="variant" :chart-height="400" />
        </el-card>
      </el-col>

      <!-- 第三列 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <wanggesuixiao-chart :selected-date="gridsuixiaoChartDate" style="width: 100%; height: 433px"
            @handle-date-change="handlesuixiaoWanggeDateChange" />
        </el-card>

        <!-- 人数及分阶薪酬占比 -->
        <el-card class="pie-chart-card2">
          <pie-chart :selected-date="pieChartDate" class="pie-chart-wrapper"
            @handle-date-change="handlePieChartDateChange" v-hasPermi="['salary:salaryDetail']" />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 0px">
      <el-col :span="8">
        <!-- 当月薪酬Top10 -->
        <el-card style="margin-top: 0px; height: 468px">
          <ranking-table style="border: 0px" ref="rankingTable" :init-date="selectedDate"
            @date-change="handleRankingDateChange" v-hasPermi="['salary:salaryDetail']" />
        </el-card>
      </el-col>

      <el-col :span="16">
        <!-- 按月份获取区域对应的随销及新增达标代维人员人数及总人数占比 -->
        <el-card style="margin-top: 0px; height: 468px">
          <suixiao-radios style="border: 0px" ref="suixiaoRadios" :init-date="selectedDate"
            @date-change="handleRankingDateChange" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  ElDatePicker,
  ElRow,
  ElCol,
  ElCard,
  ElTable,
  ElTableColumn,
  ElSelect,
  ElOption,
} from "element-plus";
import CircularChartWithFetch from "./dwxc/components/CircularChartWithFetch.vue";
import RankingTable from "./dwxc/components/RankingTable.vue";
import SalaryChart from "./dwxc/components/salaryChart.vue";
import PieChart from "./dwxc/components/pieChart.vue";
import wanggeChart from "./dwxc/components/wanggeChart.vue";
import suixiaoChart from "./dwxc/components/suixiaoChart.vue";
import wanggesuixiaoChart from "./dwxc/components/wanggesuixiaoChart.vue";
import SalaryCompositionChart from "./dwxc/components/salaryCompositionChart.vue";
import suixiaoRadios from "./dwxc/components/suixiaoRadios.vue";

export default {
  components: {
    ElDatePicker,
    ElRow,
    ElCol,
    ElCard,
    ElSelect,
    ElOption,
    CircularChartWithFetch,
    RankingTable,
    ElTable,
    ElTableColumn,
    SalaryChart,
    PieChart,
    wanggeChart,
    suixiaoChart,
    wanggesuixiaoChart,
    SalaryCompositionChart,
    suixiaoRadios,
  },
  data() {
    return {
      // 薪酬图表的独立日期
      salaryChartDate: this.formatDateToString(this.getLastMonth()),
      // 随销图表的独立日期
      suixiaoChartDate: this.formatDateToString(this.getLastMonth()),

      // 饼图的独立日期
      pieChartDate: this.formatDateToString(this.getLastMonth()),

      // 网格的独立日期
      gridChartDate: this.formatDateToString(this.getLastMonth()),
      // 网格随销图表的独立日期
      gridsuixiaoChartDate: this.formatDateToString(this.getLastMonth()),

      // 其他图表共用的日期（主要用于排名表格）
      selectedDate: this.formatDateToString(this.getLastMonth()),

      // 日期选择器配置，禁止选择当前月之后的日期
      pickerOptions: {
        disabledDate: (time) => {
          const now = new Date();
          const firstDayOfMonth = new Date(
            now.getFullYear(),
            now.getMonth(),
            1
          );
          return time.getTime() >= firstDayOfMonth.getTime();
        },
      },
      // 薪酬组成图表的日期
      salaryCompositionDate: this.formatDateToString(this.getLastMonth()),
    };
  },
  // 组件挂载后更新图表
  async mounted() {
    // Use nextTick to ensure DOM is ready
    await this.$nextTick();
    // 延迟加载图表以提高初始加载性能
    setTimeout(() => {
      this.updateCharts();
    }, 100);
  },
  methods: {
    // 更新排名表格（环形图表现在独立管理，不需要统一更新）
    async updateCharts() {
      // 更新排名表格
      const formattedDate = this.formatDate(this.selectedDate);
      await this.$nextTick(() => {
        if (this.$refs.rankingTable) {
          this.$refs.rankingTable.refresh(formattedDate);
        }
      });
    },

    // 薪酬图表日期变化处理
    handleSalaryDateChange(date) {
      console.log("Salary chart date changed:", date);
      this.salaryChartDate = date;
    },
    // 新增随销图表日期变化处理
    handleSuixiaoDateChange(date) {
      console.log("Suixiao chart date changed:", date);
      this.suixiaoChartDate = date;
    },
    handleWanggeDateChange(date) {
      console.log("Salary chart date changed:", date);
      this.gridChartDate = date;
    },
    handleWanggesuixiaoDateChange(date) {
      console.log("Salary chart date changed:", date);
      this.gridsuixiaoChartDate = date;
    },

    // 饼图日期变化处理
    handlePieChartDateChange(date) {
      console.log("Pie chart date changed:", date);
      // 确保日期格式正确
      if (date) {
        // 如果是 Date 对象，转换为字符串
        if (date instanceof Date) {
          const year = date.getFullYear();
          const month = (date.getMonth() + 1).toString().padStart(2, "0");
          this.pieChartDate = `${year}-${month}-01`;
        } else {
          // 如果已经是字符串，直接使用
          this.pieChartDate = date;
        }
        console.log("Formatted pie chart date:", this.pieChartDate);
      }
    },

    // 薪酬组成图表日期变化处理
    handleSalaryCompositionDateChange(date) {
      console.log("Salary composition date changed:", date);
      this.salaryCompositionDate = date;
    },

    // 其他图表的日期选择变化时的处理函数
    handleDateChange(date) {
      console.log("Other charts date:", date, "类型:", typeof date);

      // 处理不同格式的日期
      if (typeof date === "string") {
        // 如果是字符串格式，直接使用
        this.selectedDate = date;
      } else if (date instanceof Date) {
        // 如果是 Date 对象，格式化为字符串
        this.selectedDate = this.formatDateToString(date);
      } else {
        console.error("【index.vue】未知的日期格式:", date);
        return;
      }

      console.log("【index.vue】处理后的日期:", this.selectedDate);
      // 更新其他图表
      this.updateCharts();
    },

    // 获取上个月的日期
    getLastMonth() {
      const now = new Date();
      const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      return lastMonth;
    },

    formatDate(date) {
      // 处理不同格式的日期
      if (typeof date === "string") {
        // 如果是字符串格式 "YYYY-MM-DD"，提取 "YYYY-MM" 部分
        if (date.includes("-")) {
          return date.substring(0, 7); // "2024-06-01" -> "2024-06"
        }
        return date; // 如果已经是 "YYYY-MM" 格式
      } else if (date instanceof Date) {
        // 如果是 Date 对象，格式化为 "YYYY-MM"
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        return `${year}-${month}`;
      } else {
        console.error("【index.vue formatDate】未知的日期格式:", date);
        return "";
      }
    },

    // 格式化日期为字符串，用于传递给子组件
    formatDateToString(date) {
      // 处理不同格式的日期
      if (typeof date === "string") {
        // 如果是字符串格式，确保是 "YYYY-MM-DD" 格式
        if (date.length === 7) {
          return date + "-01"; // "2024-06" -> "2024-06-01"
        }
        return date; // 如果已经是完整格式
      } else if (date instanceof Date) {
        // 如果是 Date 对象，格式化为 "YYYY-MM-DD"
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        return `${year}-${month}-01`;
      } else {
        console.error("【index.vue formatDateToString】未知的日期格式:", date);
        return "";
      }
    },
  },
};
</script>

<style scoped>
/* 仪表盘样式 */
.dashboard {
  padding: 20px;
}

.el-card {
  margin-bottom: 8px;
}

.chart-title {
  font-size: 18px;
  font-weight: bold;
  margin-left: 20px;
}

.chart {
  height: 400px;
}

.pie-chart-card {
  padding: 0;
}

.pie-chart-card2 {
  padding: 0;
}

.pie-chart-wrapper {
  flex: 1;
  min-height: 0;
  /* 允许收缩 */
}

.pie-chart-wrapper :deep(.pie-chart) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.pie-chart-wrapper :deep(.main-wrapper) {
  flex: 1;
  height: 100%;
  max-height: none;
  max-width: none;
  width: 100%;
  box-shadow: none;
}

.pie-chart-wrapper :deep(.content-container) {
  height: 100%;
  padding: 20px;
}

.pie-chart-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  height: 466px;
}

.pie-chart-card2 :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  height: 468px;
}

.chart-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>
